package com.volunteer.service.impl;

import com.volunteer.entity.Showcase;
import com.volunteer.model.vo.HomeDataVO;
import com.volunteer.service.HomeService;
import com.volunteer.service.CarouselService;
import com.volunteer.service.ActivityService;
import com.volunteer.service.ShowcaseService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;
import java.util.List;

/**
 * 首页服务实现类
 */
@Service
@RequiredArgsConstructor
public class HomeServiceImpl implements HomeService {

    private final CarouselService carouselService;
    private final ActivityService activityService;
    private final ShowcaseService showcaseService;

    @Override
    public CompletableFuture<HomeDataVO> getHomeData() {
        // 异步获取轮播图数据
        CompletableFuture<List<HomeDataVO.CarouselVO>> carouselsFuture = CompletableFuture
                .supplyAsync(carouselService::getCarouselList);

        // 异步获取热门活动数据
        CompletableFuture<List<HomeDataVO.ActivityVO>> activitiesFuture = CompletableFuture
                .supplyAsync(activityService::getHotActivities);

        CompletableFuture<List<Showcase>> showcaseFuture = CompletableFuture
                .supplyAsync(showcaseService::getShowcaseList);

        // 组合异步任务的结果
        return CompletableFuture.allOf(carouselsFuture, activitiesFuture)
                .thenApply(v -> {
                    HomeDataVO homeData = new HomeDataVO();
                    try {
                        homeData.setCarousels(carouselsFuture.get());
                        homeData.setHotActivities(activitiesFuture.get());
                        homeData.setShowcases(showcaseFuture.get());
                    } catch (Exception e) {
                        // 记录错误日志
                        e.printStackTrace();
                    }
                    return homeData;
                });
    }
}
